package com.hmdp.handler;


import com.hmdp.config.mq.MqConstants;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.service.IVoucherOrderService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class VoucherOrderHandler {
    private final IVoucherOrderService voucherOrderService;

    @RabbitListener( bindings = @QueueBinding(
            value = @Queue(value = MqConstants.Queue.VOUCHER_QUEUE, durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.VOUCHER_EXCHANGE, type = ExchangeTypes.TOPIC, durable = "true"),
            key = MqConstants.Key.VOUCHER_KEY
    ))
    public void listenVoucherOrder(VoucherOrder order, Message message, Channel channel) {

        try {
            voucherOrderService.createVoucherOrder( order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

}
